// websocket.js
class WebSocketService {
  constructor() {
    this.socket = null
    this.isConnected = false
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 100
    this.reconnectDelay = 3000 // 3 seconds
  }

  connect(url) {
    return new Promise((resolve, reject) => {
      if (!this.socket || this.socket.readyState === WebSocket.CLOSED) {
        this.socket = new WebSocket(url)

        this.socket.onopen = () => {
          console.log('WebSocket connection established')
          this.isConnected = true
          this.reconnectAttempts = 0 // 重置重连次数
          this.sendMessage('hello server friend!')
          resolve()
        }

        this.socket.onmessage = (event) => {
          console.log('Message from server:', event.data)
        }

        this.socket.onerror = (error) => {
          console.error('WebSocket error:', error)
          this.isConnected = false
          reject(error)
        }

        this.socket.onclose = () => {
          console.log('WebSocket connection closed')
          this.isConnected = false
          this.reconnect()
        }
      } else {
        resolve()
      }
    })
  }

  sendMessage(message) {
    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message)
    } else {
      console.log('WebSocket is not open')
    }
  }

  close() {
    if (this.socket) {
      this.socket.close()
    }
  }

  getConnectionStatus() {
    return this.isConnected
  }

  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`Reconnecting... Attempt ${this.reconnectAttempts}`)
      setTimeout(() => {
        this.connect(this.socket.url).catch((err) => {
          console.warn('Reconnection failed: ', err)
          this.reconnect() // 尝试再次重连
        })
      }, this.reconnectDelay)
    } else {
      console.warn('Max reconnect attempts reached.')
    }
  }
}

export default new WebSocketService()
